import { FormValueType } from '@/pages/User/List/components/UpdateForm';
import { PermsItem, UserItem } from '@/pages/User/List/data';
import { queryUserPerms, updateUserPerms } from '@/pages/User/List/service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { EditableProTable, ProColumns } from '@ant-design/pro-components';
import { message, Modal, Switch } from 'antd';
import React, { useEffect, useState } from 'react';

type PermsFormProps = {
  permsModalVisible: boolean;
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  values: Partial<UserItem>;
};

const PermsForm: React.FC<PermsFormProps> = (props) => {
  // 表格内容，使用useEffect关联选中的行，更改时自动更新数据
  const [tableListDataSource, setTableListDataSource] = useState<PermsItem[]>([]);
  // 选中行的钩子
  const selectValue = props.values;
  // 取消
  const { onCancel } = props;
  const [isUpdate, setIsUpdate] = useState<boolean>(true)
  /**
   * 更新节点
   *
   * @param checked
   * @param mid
   * @param uid
   * @param perms_type   1: 是查看权限；2：是新增权限；3：是修改权限；4：是删除权限
   */

  const handleUpdate = async (checked?: any, mid?: any, uid?: any, perms_type?: any) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateUserPerms({
        checked: checked,
        mid: mid,
        uid: uid,
        permsType: perms_type,
      });
      if (res && res.status === 'done') {
        hide();
        message.success(res.message);
        if (isUpdate){
          setIsUpdate(false)
        }else{
          setIsUpdate(true)
        }
        return true;
      } else {
        hide();
        message.error(res.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('更新失败，请重试！');
      return false;
    }
  };

  // 获取数据
  useEffect(() => {
    const fetchPermsInfo = async () => {
      const res = await queryUserPerms({ uid: props.values.id });
      if (res.status === "done") {
        const data = res?.data || [];
        setTableListDataSource(data);
      }
    };
    fetchPermsInfo().then();
  }, [selectValue, isUpdate]);

  // 菜单列
  const columns: ProColumns<PermsItem>[] = [
    // 列表字段
    // 菜单名
    {
      title: '菜单名称',
      dataIndex: 'title',
      valueType: 'text',
      hideInSearch: true,
      editable: false,
    },
    // 是否展示
    {
      title: '状态',
      width: 80,
      dataIndex: 'show',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: {
        true: { text: '显示', status: 'Success' },
        false: { text: '隐藏', status: 'Warning' },
      },
      align: 'center',
      editable: false,
    },
    // 查看权限
    {
      title: '查看',
      width: 80,
      dataIndex: 'read',
      key: 'read',
      hideInSearch: true,
      align: 'center',
      render: (o, record) => (
        <span>
          <Switch
            key={'read' + record.id}
            checked={record.read}
            onChange={(checked) => handleUpdate(checked, record.id, props.values.id, "read")}
          />
        </span>
      ),
    },
    // 新增权限
    {
      title: '新增',
      width: 80,
      dataIndex: 'add',
      hideInSearch: true,
      align: 'center',
      render: (o, record) => (
        <span>
          <Switch
            checked={record.add}
            onChange={(checked) => {
              console.log(checked, "fuck")
              handleUpdate(checked, record.id, props.values.id, "add")
            }}
          />
        </span>
      ),
    },
    // 修改权限
    {
      title: '修改',
      width: 80,
      dataIndex: 'edit',
      hideInSearch: true,
      align: 'center',
      render: (o, record) => (
        <span>
          <Switch
            checked={record.edit}
            onChange={(checked) => handleUpdate(checked, record.id, props.values.id, "update")}
          />
        </span>
      ),
    },
    // 删除权限
    {
      title: '删除',
      width: 80,
      dataIndex: 'del',
      hideInSearch: true,
      align: 'center',
      render: (o, record) => (
        <span>
          <Switch
            checked={record.del}
            onChange={(checked) => handleUpdate(checked, record.id, props.values.id, "delete")}
          />
        </span>
      ),
    },
  ];

  return (
    <Modal
      destroyOnClose
      width={1200}
      title={props.values.username + ' 的权限'}
      open={props.permsModalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <p style={{ color: 'red', paddingLeft: '28px' }}>
        <ExclamationCircleOutlined />
        用户的权限包括自身的权限以及角色授予的权限，此处仅管理用户自身的权限。
      </p>
      <EditableProTable<PermsItem>
        expandable={{
          // 使用 request 请求数据时无效
          defaultExpandAllRows: false,
        }}
        // 新增一行按钮，取消
        recordCreatorProps={false}
        // 分页
        pagination={false}
        //headerTitle="菜单列表"
        // actionRef={actionRef}
        rowKey="id"
        // 搜索栏关闭
        search={false}
        // 最大高度
        scroll={{
          y: 600,
        }}
        // 修改设置
        // editable={{
        //   type: 'multiple',
        //   //editableKeys,
        //   // 当表格内容修改时，即时更新到后台
        //   onValuesChange: async (record, recordList) => {
        //     // 保存修改
        //     try {
        //       const res = await updateUserPerms({
        //         ...recordList,
        //       });
        //       if (res && res.status == "done"){
        //         message.success(res.message);
        //         return true
        //       }else {
        //         message.error(res.message)
        //         return false
        //       }
        //     } catch (error){
        //       message.error("更新失败，请重试！")
        //       return false
        //     }
        //   },
        // }}
        // 表格数据源
        // @ts-ignore
        // request={queryUserPerms}
        value={tableListDataSource}
        columns={columns}
      />
    </Modal>
  );
};

export default PermsForm;
